package service

import (
	"CHATROOM/message"
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

const (
	entering = iota
	leaving
	chating
	other
)

// 所有聊天室用户
var All_users = make(map[string]*User)

var upgrader = websocket.Upgrader{}

func WebsocketMessage(c *gin.Context) {
	username := c.Query("username")
	roomID := c.Query("roomID")
	fmt.Println("ws_username:", username, roomID)

	//升级为websocket
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "系统异常：" + err.Error(),
		})
		return
	}
	defer conn.Close()
	//1.登录成功
	//1.1存储用户
	newUser := &User{
		Username: username,
		Rooms:    roomID,
		Conn:     conn,
	}
	All_users[username] = newUser

	//1.2统计一下,这个房间有多少玩家了
	var roomUsers []string
	for key, value := range All_users {
		if value.Rooms == roomID {
			roomUsers = append(roomUsers, key)
		}
	}
	//1.3广播出去,该房间有用户来了
	for _, value := range All_users {
		if value.Rooms == roomID {
			message := message.GCMessageEnter{
				MessageType:    entering,
				MessageContent: "welcome " + username,
				User:           roomUsers,
			}
			jsonData, err := json.Marshal(message)
			if err != nil {
				log.Println("Error marshalling JSON:", err)
				return
			}
			err = value.Conn.WriteMessage(websocket.TextMessage, jsonData)
			if err != nil {
				log.Println("Error writing message to WebSocket:", err)
				return
			}
		}
	}

	//接受消息的处理
	for {
		ms := new(message.CGMessageChat)
		err := conn.ReadJSON(ms)
		if err != nil {
			log.Printf("Read Error:%v\n", err)
			return
		}
		//1.判断消息类型
		fmt.Println("ms", ms, ms.MessageType, ms.MessageContent)

		//2.消息分发
		if ms.MessageType == leaving {
			//2.1离开
			delete(All_users, username)
			//1.2统计一下,这个房间有多少玩家了
			var roomUsers []string
			for key, value := range All_users {
				if value.Rooms == roomID {
					roomUsers = append(roomUsers, key)
				}
			}
			//1.3广播出去,该房间有用户来了
			for _, value := range All_users {
				if value.Rooms == roomID {
					message := message.GCMessageLeave{
						MessageType:    leaving,
						MessageContent: "886 " + username,
						User:           roomUsers,
					}
					jsonData, err := json.Marshal(message)
					if err != nil {
						log.Println("Error marshalling JSON:", err)
						return
					}
					err = value.Conn.WriteMessage(websocket.TextMessage, jsonData)
					if err != nil {
						log.Println("Error writing message to WebSocket:", err)
						return
					}
				}
			}
		} else if ms.MessageType == chating {
			//2.2对话
			for _, value := range All_users {
				if value.Rooms == roomID {
					message := message.GCMessageChat{
						MessageType:    chating,
						MessageContent: username + "says:" + ms.MessageContent,
					}
					jsonData, err := json.Marshal(message)
					if err != nil {
						log.Println("Error marshalling JSON:", err)
						return
					}
					err = value.Conn.WriteMessage(websocket.TextMessage, jsonData)
					if err != nil {
						log.Println("Error writing message to WebSocket:", err)
						return
					}
				}
			}
		}

		//3.消息处理

		// // 判断用户是否属于消息体的房间
		// _, err = model.GetUserRoomByUserIdentityRoomIdentity(uc.ID, ms.RoomIdentity)
		// if err != nil {
		// 	log.Printf("UserIdentity:%v RoomIdentity:%v Not Exits\n", uc.ID, ms.RoomIdentity)
		// 	return
		// }

		// // 获取在特定房间的在线用户
		// userRooms, err := model.GetUserRoomByRoomIdentity(ms.RoomIdentity)
		// if err != nil {
		// 	log.Printf("[DB ERROR]:%v\n", err)
		// 	return
		// }

	}

}
